/**
 *  This file is part of TaoBaoItemImporter.
 *
 *   TaoBaoItemImporter is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   TaoBaoItemImporter is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with TaoBaoItemImporter.  If not, see <http://www.gnu.org/licenses/>. 
 */
package com.googlecode.ulysses.taobao.importer;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;

import com.googlecode.ulysses.taobao.Connector;
import com.googlecode.ulysses.taobao.Constants;
import com.googlecode.ulysses.taobao.data.Item;
import com.mongodb.DBCollection;
import com.mongodb.MongoException;

/**
 * Launches an importing job.
 * 
 * @author Ulysses <robman1070@gmail.com>
 * 
 */
public class Workman {

	/**
	 * @param args
	 * @throws MongoException
	 * @throws IOException
	 */
	@SuppressWarnings("static-access")
	public static void main(String[] args) throws MongoException, IOException {

		/* Get arguments */
		String jsonFile = "";
		String host = Constants.DEFAULT_MONGO_HOST;
		Constants.ItemType itemType;
		int port = Constants.DEFAULT_MONGO_PORT;
		String user = "";
		String security = "";
		String db = "";
		String coll = "";

		Options options = new Options();
		options.addOption(OptionBuilder.isRequired().hasArg()
				.withDescription("The path to a Json file for importing")
				.withLongOpt("file").create("f"));
		options.addOption(OptionBuilder
				.isRequired()
				.hasArg()
				.withDescription(
						"An integer indicating the type of the item to import. See com.googlecode.ulysses.taobao.Constants.ItemType")
				.withLongOpt("type").create("t"));
		options.addOption(OptionBuilder.isRequired(false).hasArg()
				.withDescription("[Optional] Mongodb host, default localhost")
				.withLongOpt("host").create("h"));
		options.addOption(OptionBuilder
				.isRequired(false)
				.hasArg()
				.withDescription(
						"[Optional] Mongodb port number, default 27017")
				.withLongOpt("port").create("p"));
		options.addOption(OptionBuilder
				.isRequired(false)
				.hasArg()
				.withDescription(
						"[Optional] Mongodb login user, such as tester")
				.withLongOpt("user").create("u"));
		options.addOption(OptionBuilder.isRequired(false).hasArg()
				.withDescription("[Optional] Mongodb login password")
				.withLongOpt("password").create("s"));
		options.addOption(OptionBuilder.isRequired().hasArg()
				.withDescription("Mongodb database name")
				.withLongOpt("database").create("d"));
		options.addOption(OptionBuilder.isRequired().hasArg()
				.withDescription("Mongodb collection name")
				.withLongOpt("collection").create("c"));

		CommandLineParser parser = new GnuParser();
		try {
			CommandLine line = parser.parse(options, args);
			jsonFile = line.getOptionValue("file");
			itemType = Constants.ITEM_TYPES.toItemType(line
					.getOptionValue("type"));
			host = line.getOptionValue("host");
			port = line.getOptionValue("port") == null ? Constants.DEFAULT_MONGO_PORT
					: Integer.parseInt(line.getOptionValue("port"));
			user = line.getOptionValue("user");
			security = line.getOptionValue("password");
			db = line.getOptionValue("database");
			coll = line.getOptionValue("collection");
		} catch (org.apache.commons.cli.ParseException e) {
			System.err.print("Parsing failed.  Reason: " + e.getMessage());
			System.err.println();
			// automatically generate the help statement
			HelpFormatter formatter = new HelpFormatter();
			Workman workman = new Workman();
			formatter.printHelp(workman.getClass().getCanonicalName(), options);
			return;
		}

		Connector conn = null;
		if (user != null && security != null)
			conn = new Connector(host, port, user, security.toCharArray());
		else
			conn = new Connector(host, port);

		/* Get the collection handler */
		conn.connect();
		DBCollection collObj = conn.getCollectionObj(db, coll);

		int itemImported = 0;

		/* 1. Access a file of jsons */
		FileInputStream fstream = new FileInputStream(jsonFile);
		DataInputStream in = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine; // a string of json object
		while ((strLine = br.readLine()) != null && ! strLine.isEmpty()) {
			/* Create the item importer for the given type. */
			ItemImporter importer = null;
			switch (itemType) {
			case ITEM_TYPE_DIGITAL:
				importer = new DigitalItemImporter();
				break;
			case ITEM_TYPE_CLOTHES:
				importer = new ClothesItemImporter();
				break;
			case ITEM_TYPE_BAG:
				importer = new BagItemImporter();
				break;
			default:
				System.err.println("ERROR: Unknown item type. Exit.");
				return;
			}

			/* 2. Convert a json to a java object. */
			Item item = importer.jsonToItem(strLine);

			/* 3. Import the java object as a collection into Mongodb. */
			importer.importItemToCollection(collObj, item);

			itemImported++;
		}
		in.close();

		/* Report */
		System.err.print("INFO: Imported: " + itemImported + " items of type "
				+ itemType.toString() + ".\n");
		System.err.println();

		/* Clean up */
		conn.getMongo().close();

	}

}
